import pdb
import random
import time
import uuid
from datetime import timedelta, datetime

from sqlalchemy import func

from app.models import db
from app.models.ticket_lib import Ticket
from app.models.train_station_lib import TrainStation


class Order(db.Model):
    __tablename__ = 'order'

    id = db.Column(db.Integer, primary_key=True)
    order_no = db.Column(db.String(120), unique=True, nullable=False)
    price = db.Column(db.Numeric(8, 2))
    payment_time = db.Column(db.DateTime)
    state = db.Column(db.Integer, default=0)
    passenger_id = db.Column(db.Integer, db.ForeignKey('passenger.id'), nullable=False, index=True)
    created_at = db.Column(db.DateTime, default=func.now())
    updated_at = db.Column(db.DateTime, default=func.now())

    passenger = db.relationship('Passenger', backref=db.backref('orders'))

    def __repr__(self):
        return f'<Order {self.id}>'

    @classmethod
    def setOrderState(cls, order_no, passenger_id, **kwargs):
        order = cls.query.filter_by(order_no=order_no, passenger_id=passenger_id).first()
        if order:
            # 更新订单的属性
            for key, value in kwargs.items():
                setattr(order, key, value)
                if key == 'state' and value == 1:
                    for ticket in order.tickets:
                        Ticket.updateState(ticket)  # Update state to 1
            # 提交更改到数据库
            db.session.commit()
            return order
        else:
            # 处理订单未找到的情况
            return None


def generate_unique_id(length=4):
    # 获取当前的秒级时间戳
    timestamp_seconds = int(time.time())

    # 生成 4 位随机数
    random_number = random.randint(0, 10 ** length - 1)

    # 确保随机数是 4 位数字
    random_number_str = str(random_number).zfill(length)

    # 生成唯一标识符
    unique_id = f"{timestamp_seconds}{random_number_str}"
    return unique_id


def generateOrder(params, passenger_id):
    # Create a new Order object
    order = Order(
        order_no=generate_unique_id(5),
        passenger_id=passenger_id
    )

    for e in params['tickets']:
        # 创建Ticket对象
        ticket = Ticket.generateTicket(e, passenger_id)
        # 计算起始站和终点站
        from_station = TrainStation.query.filter_by(train_no=ticket.train_no, station_name=ticket.from_station).one()
        to_station = TrainStation.query.filter_by(train_no=ticket.train_no, station_name=ticket.to_station).one()
        # 计算区间价格
        train_stations = TrainStation.query.filter(
            TrainStation.train_no == ticket.train_no,
            TrainStation.index.between(from_station.index, to_station.index)
        ).all()
        ticket.price = sum(e.price for e in train_stations)
        # 计算座位号
        seat_count = db.session.query(func.count(Ticket.id)).filter_by(
            train_no=ticket.train_no,
            date=ticket.date
        ).scalar()
        ticket.seat_no = seat_count + 1

        # 转换时间 计算出发时间
        interval_days = (
                datetime.strptime(ticket.date, "%Y/%m/%d") - datetime.combine(from_station.departure_time.date(),
                                                                              datetime.min.time())).days
        ticket.departure_time = from_station.departure_time + timedelta(days=interval_days)
        ticket.arrival_time = to_station.arrival_time + timedelta(days=interval_days)

        order.tickets.append(ticket)

    order.price = sum(ticket.price for ticket in order.tickets)

    return order


